<template>
  <div class="pageOut">
    <div class="pageIn">
      <el-form :inline="true" :model="formSearch" size="small">
        <el-form-item>
          <el-input
            v-model="formSearch.menu_name"
            placeholder="商品名称"
            clearable
          ></el-input>
        </el-form-item>
        <!-- <el-form-item>
          <el-date-picker
            value-format="yyyy-MM-dd"
            v-model="formSearch.time"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item> -->
        <el-form-item>
          <el-button icon="el-icon-search" @click="search">查询</el-button>

          <el-button
            icon="el-icon-plus"
            v-if="permission.add"
            type="primary"
            @click="handleAdd"
            >添加</el-button
          >
        </el-form-item>
      </el-form>
      <el-table
        border
        ref="table"
        :height="height - 170"
        :data="tableData"
        :header-cell-style="{ background: '#FAFAFA', color: '#606266' }"
        v-loading="loading"
        element-loading-background="rgba(255, 255, 255, 0.5)"
        style="width: 100%"
      >
        <el-table-column prop="name" label="名称"></el-table-column>
        <el-table-column
          prop="commodity"
          label="图文介绍"
          :show-overflow-tooltip="tooltip"
        >
          <template slot-scope="scope">
            <el-link type="primary" @click="editorClick(scope.row)"
              >预览</el-link
            >
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="保存时间"></el-table-column>

        <el-table-column label="操作" width="320" align="center">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              @click="handleEdit(scope.row)"
              v-show="permission.edit"
              >编辑</el-button
            >
            <el-button
              :type="scope.row.usageStatus == 2 ? 'primary' : 'danger'"
              size="mini"
              @click="goMenuTastes(scope.row)"
              v-show="permission.MenuTastes"
              >{{ scope.row.usageStatus == 2 ? "使用" : "取消使用" }}</el-button
            >
            <el-button
              type="danger"
              size="mini"
              @click="handleDel(scope.row.id)"
              v-show="permission.del"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="pageSizes"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>

      <!-- 商品添加和商品编辑 -->
      <el-dialog
        :title="type === 'add' ? '添加' : '修改'"
        :visible.sync="visible"
        width="40%"
        @close="onCancel('ruleForm')"
      >
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          size="mini"
          label-width="110px"
          class="form-drawer__main"
        >
          <el-form-item label="名称" prop="name" style="margin-bottom: 30px">
            <el-input
              class="formInput"
              clearable
              v-model="ruleForm.name"
              placeholder="请输入名称"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="产品图文"
            prop="content"
            style="margin-bottom: 30px"
          >
            <Editor
              @onEditorChange="onEditorChange"
              :content="ruleForm.content"
              ref="editor"
            />
          </el-form-item>
          <el-form-item label="是否使用">
            <el-switch v-model="ruleForm.type"> </el-switch>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="onCancel('ruleForm')" size="small"
            >取 消</el-button
          >
          <el-button
            type="primary"
            size="small"
            @click="onConfirm('ruleForm')"
            :loading="confirmLoading"
            >{{ confirmLoading ? "提交中 ..." : "确 定" }}</el-button
          >
        </span>
      </el-dialog>

      <el-dialog
        append-to-body
        title="图文预览"
        :visible.sync="coupoDeis"
        width="50%"
        @close="editorColse"
      >
        <Editor
          @onEditorChange="onEditorChange"
          :content="ruleForm.content"
          :disabled="true"
          ref="editor"
        />

        <span slot="footer" class="dialog-footer">
          <el-button @click="coupoDeis = false">取 消</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  introduceList,
  introduceDel,
  introduceAdd,
  introduceEdit,
  introduceDetail,
  allGoods,
  MAIN,
  introduceUsageUpdate,
  typeList,
  goodsSel,
} from "../../utils/api";
import UploadImage from "../../components/UploadImage";
import UploadImg from "../../components/UploadImg";
import Editor from "../../components/Editor";
export default {
  name: "GoodsDefault",
  props: ["height"],
  components: {
    UploadImg,
    UploadImage,
    Editor,
  },
  data() {
    return {
      dialogTotal: 0,
      goodsDialog: false,
      options: {
        type: "picture-card",
        limit: 5,
      }, //上传图片配置项
      goodsRow: [],

      casOptions: [],
      casProps: {
        value: "id",
        label: "name",
        children: "child",
      },
      tableData: [
        {
          id: 1,
        },
      ],
      cleckData: [],
      tooltip: true, //内容过长被隐藏时显示 tooltip
      loading: true, //显示加载表格
      pageSize: 10, //每页多少条
      currentPage: 1, //当前第几页
      pageSizes: [10, 20, 30, 40, 50], //每页选择条数
      total: 0, //共多少条
      permission: {
        add: false,
        edit: false,
        del: false,
        MenuTastes: false,
      }, //权限
      errImg: 'this.src="' + require("../../../static/img/user.png") + '"',
      formSearch: {
        merchant_id: "",
        menu_name: "",
        priceMin: "",
        priceMax: "",
        time: "",
      }, //搜索
      userinfo: {},
      casOptions: [],
      doaPageNumber: 1,
      casProps: {
        value: "id",
        label: "name",
        children: "child",
      },
      bannerType: [
        {
          id: 1,
          name: "商品",
        },
        {
          id: 2,
          name: "活动",
        },
      ],
      //编辑弹窗
      visible: false,
      confirmLoading: false,
      type: "",
      currentRow: {}, //当前行数据信息
      ruleForm: {
        content: "",
        name: "",
        type: true,
      }, //添加和修改的表单
      dialogSearch: {
        name: "",
        merchant_id: "",
      },
      coupoDeis: false,
      rules: {
        content: [{ required: true, message: "请输入图文", trigger: "blur" }],
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
      },
      merchant: {}, //商家列表
      cate: {}, //商品分类列表
    };
  },

  mounted() {
    this.getResource();

    this.cateSelects(); //商品分类列表
    this.getGoodsSel();
  },
  methods: {
    selectAll() {},
    getGoodsSel() {
      let params = {
        name: this.dialogSearch.name,
        goodsTypeTwo: this.dialogSearch.merchant_id[1] || "",
        pageSize: 10,
        pageNumber: this.doaPageNumber,
      };
      this.postRequest(goodsSel, params, MAIN).then((res) => {
        if (res.code === 200) {
          this.cleckData = res.data.list;
          this.dialogTotal = res.data.count;
        }
      });
    },
    dailogHandleSizeChange(val) {
      this.doaPageNumber = val;
      this.getGoodsSel();
    },
    //富文本框
    onEditorChange(e) {
      this.ruleForm.content = e;
    },
    casHandleChange() {},
    editorColse() {
      // console.log(this.$refs.editor);
      if (this.$refs.editor) {
        // console.log('dd');
        this.$refs.editor.clear();
      }
    },
    // 商品分类列表
    cateSelects() {
      this.postRequest(typeList, MAIN).then((res) => {
        if (res.code == 200) {
          this.casOptions = res.data;
        }
      });
    },
    handleSelectionChange(selection) {
      this.goodsRow = selection;
      if (selection.length > 1) {
        let del_row = selection.shift();
        this.$refs.multipleTable.toggleRowSelection(del_row, false);
      }
      console.log(this.goodsRow);
    },
    //获取权限资源
    getResource() {
      // console.log(this.$route.name);
      this.loading = true;
      const userinfo = JSON.parse(sessionStorage.getItem("userInfo")); //解密,获取用户登录信息
      this.userinfo = userinfo;
      let arr = userinfo.menu_id.split(",");
      // console.log(arr)
      // 新增 119
      // 修改 120
      // 删除 122
      // 取消使用 121
      if (arr.indexOf("119") > -1) {
        this.permission.add = true;
      }
      if (arr.indexOf("120") > -1) {
        this.permission.edit = true;
      }

      if (arr.indexOf("122") > -1) {
        this.permission.del = true;
      }

      if (arr.indexOf("121") > -1) {
        this.permission.MenuTastes = true;
      }

      this.getData();
      this.merchantSelects(); //商家下拉列表
    },

    //   商家下拉列表
    merchantSelects() {
      this.postRequest(allGoods, {}, MAIN).then((res) => {
        if (res.code == 200) {
          this.merchant = res.data;
        }
      });
    },

    // 商品分类列表
    cateSelects() {
      this.postRequest(typeList, MAIN).then((res) => {
        if (res.code == 200) {
          this.casOptions = res.data;
        }
      });
    },
    //获取初始数据
    getData() {
      this.loading = true;
      let params = {
        userId: this.userinfo.id,
        name: this.formSearch.menu_name,
        pageNumber: this.currentPage,
        pageSize: this.pageSize,
      };

      this.postRequest(introduceList, params, MAIN).then((res) => {
        if (res.code == 200) {
          this.tableData = res.data.list;
          this.total = res.data.count;
          this.loading = false;
          this.$nextTick(() => {
            //避免表格表头样式错乱
            if (this.$refs.table) this.$refs.table.doLayout();
          });
        }
      });
    },
    editorClick(row) {
      this.coupoDeis = true;
      this.postRequest(introduceDetail, { id: row.id }, MAIN).then((res) => {
        if (res.code === 200) {
          this.ruleForm.content = res.data.introduce;
        }
      });
    },
    //分页
    handleSizeChange(val) {
      //每页 ${val} 条
      this.pageSize = val;
      this.getData();
    },
    handleCurrentChange(val) {
      //当前页
      this.currentPage = val;
      this.getData();
    },
    //查询
    search() {
      this.getData();
    },
    //新增
    handleAdd() {
      this.type = "add";
      this.currentRow = {};
      this.visible = true;
    },
    //编辑
    handleEdit(row) {
      this.type = "edit";
      this.postRequest(introduceDetail, { id: row.id }, MAIN).then((res) => {
        if (res.code === 200) {
          this.currentRow = row;
          this.ruleForm = {
            name: row.name,
            content: res.data.introduce,
            type: row.usageStatus == 1,
          };
          this.visible = true;
        }
      });
    },

    //删除
    handleDel(id) {
      let parm = {
        id: id,
        userId: this.userinfo.id,
      };
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.postRequest(introduceDel, parm, MAIN).then((res) => {
            if (res.code == 200) {
              this.$notify({
                title: "删除成功",
                message: res.msg,
                type: "success",
              });
              this.getData();
            }
          });
        })
        .catch(() => {});
    },

    onConfirm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.confirmLoading = true;
          // setTimeout(() => this.onCancel(formName), 1000);
          if (this.type == "add") {
            this.addMenu();
          } else if (this.type == "edit") {
            this.editMenu();
          }
        } else {
          return false;
        }
      });
    },
    // 添加
    addMenu() {
      let params = {
        userId: this.userinfo.id,
        name: this.ruleForm.name,
        introduce: this.ruleForm.content,
        usageStatus: this.ruleForm.type ? 1 : 2,
      };

      this.postRequest(introduceAdd, params, MAIN).then((res) => {
        // console.log(res);
        this.confirmLoading = false;
        if (res.code == 200) {
          this.$notify({
            title: "添加成功",
            message: res.msg,
            type: "success",
          });
        }
        this.onReset();
        this.getData();
      });
    },
    // 编辑
    editMenu() {
      let params = {
        id: this.currentRow.id,
        userId: this.userinfo.id,
        name: this.ruleForm.name,
        introduce: this.ruleForm.content,
        usageStatus: this.ruleForm.type ? 1 : 2,
      };

      this.postRequest(introduceEdit, params, MAIN).then((res) => {
        // console.log(res);
        this.confirmLoading = false;
        if (res.code == 200) {
          this.$notify({
            title: "编辑成功",
            message: res.msg,
            type: "success",
          });
        }
        this.onReset();
        this.getData();
      });
    },
    // 关闭弹框
    onCancel(formName) {
      this.$refs[formName].resetFields();
      this.goodsRow = [];
      this.onReset();
    },
    //清空重置表单
    onReset() {
      this.visible = false;

      if (this.$refs.editor) this.$refs.editor.clear();
      this.confirmLoading = false;
      this.ruleForm = {
        content: "",
        name: "",
        type: 1,
      };
    },

    // 下架
    goMenuTastes(row) {
      let parm = {
        id: row.id,
        usageStatus: row.usageStatus == 1 ? 2 : 1,
        userId: this.userinfo.id,
      };
      this.$confirm("确认修改?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.postRequest(introduceUsageUpdate, parm, MAIN).then((res) => {
          if (res.code == 200) {
            this.$notify({
              message: res.msg,
              type: "success",
            });
            this.getData();
          }
        });
      });
    },
  },
};
</script>

<style scoped>
/deep/ .el-input-group__append,
.el-input-group__prepend {
  background-color: #1890ff;
  color: #fff;
  cursor: pointer;
}
.formInput {
  width: 300px;
}
.pageBox {
  width: 100%;
  margin-top: 30px;
  display: flex;
  justify-content: center;
}
/deep/ .el-input--mini .el-input__inner {
  height: 32px;
  line-height: 32px;
}
/deep/ input::-webkit-outer-spin-button,
/deep/ input::-webkit-inner-spin-button {
  -webkit-appearance: none;
}
/deep/ input[type="number"] {
  -moz-appearance: textfield;
}

/deep/ .el-upload-list--picture-card .el-upload-list__item {
  width: 121px;
  height: 121px;
}
/deep/ .el-upload--picture-card {
  width: 121px;
  height: 121px;
  line-height: 130px;
}
</style>
